/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 struct ListNode {
         int val;
        ListNode *next;
         ListNode() : val(0), next(nullptr) {}
         ListNode(int x) : val(x), next(nullptr) {}
         ListNode(int x, ListNode *next) : val(x), next(next) {}
     };
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (!head) return nullptr; // 如果链表为空，直接返回 nullptr

        ListNode* cur = head;
        int n = 1;
        // 计算链表长度
        while (cur->next) {
            cur = cur->next;
            n++;
        }
        // 连接成环
        cur->next = head;
        // 找到新的尾节点
        for (int i = 0; i < n - k % n; i++) {
            cur = cur->next;
        }
        // 断开环，返回新的头节点
        head = cur->next;
        cur->next = nullptr;
        return head;
    }
};